/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：
* CreateTime：2020-04-26 17:45:33
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace TinyToolKit
{
    public static partial class TinyUtility
    {
        public static class File
        {
            #region LoadFile
            /// <summary>
            /// 加载本地文本
            /// </summary>
            /// <param name="filePath">文本的保存路径</param>
            /// <returns>返回文本数据</returns>
            public static string ReadAllText(string filePath) 
            {
                return !System.IO.File.Exists(filePath) ? string.Empty : System.IO.File.ReadAllText(filePath);
            } 
            
            /// <summary>
            /// 保存文本
            /// </summary>
            /// <param name="filePath">文本的保存路径</param>
            /// <returns>返回文本数据</returns>
            public static void WriteAllText(string filePath,string contents)  
            {
                if (string.IsNullOrEmpty(filePath))  return;

                string dirPath = System.IO.Path.GetDirectoryName(filePath);
                if (string.IsNullOrEmpty(dirPath) == false && !Directory.Exists(dirPath))
                    Directory.CreateDirectory(dirPath);
                
                if(System.IO.File.Exists(filePath))
                    System.IO.File.Delete(filePath);
                else
                    System.IO.File.Create(filePath).Dispose();
                
                System.IO.File.WriteAllText(filePath,contents);
            } 
            
            /// <summary>  
            /// 加载本地文本为字节
            /// </summary>
            /// <param name="filePath">本地文本的存储路径</param>
            /// <returns>返回文本数据的字节数组</returns>
            public static byte[] LoadByteFile(string filePath)     
            {   
                if (!System.IO.File.Exists(filePath))
                {
                    TLogTool.Error("该路径下文件不存在：" + filePath);
                    return null;
                }
                
                FileStream fs = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();
                fs.Dispose();
                
                return data;
            }

            /// <summary>
            /// 加载本地文本为UTF8格式的字符串
            /// </summary>
            /// <param name="filePath">本地文本的存储路径</param>
            /// <returns>返回UTF8格式的字符串</returns>
            public static string LoadTextFile(string filePath) 
            {
                byte[] data = LoadByteFile(filePath);
                return data != null ? Encoding.UTF8.GetString(data, 0, data.Length) : string.Empty;
            }
             
            /// <summary>
            /// 从指定路径加载本地图片
            /// </summary>
            /// <param name="picPath">本地图片的存储路径</param>
            /// <returns>返回本地图片的Texture2D</returns>
            public static Texture2D LoadPicture(string picPath,int width,int height)
            {
                if (string.IsNullOrEmpty(picPath) || System.IO.File.Exists(picPath) == false) return null;
                if (!TextureHelper.IsImage(System.IO.Path.GetExtension(picPath))) return null;
                
                var buffer = LoadByteFile(picPath);
                var tex = TextureHelper.ConvertByteToTexture2D(buffer,width,height);
                tex.name = System.IO.Path.GetFileNameWithoutExtension(picPath);

                return tex;
            }
            
            /// <summary>
            /// 异步加载本地或网络的字节文件
            /// </summary>
            /// <param name="url">文件的地址</param>
            /// <param name="callback">加载完文件后的回调处理函数</param>
            public static void LoadByteFileAsync(string url, Action<byte[]> callback) 
            {
                TinyTool.Instance.StartCoroutine(LoadByteAsync(url, callback));
            }
            
            /// <summary>
            /// 异步加载本地或网络的文本文件
            /// </summary>
            /// <param name="url">文本文件的地址</param>
            /// <param name="callback">加载完文件后的回调处理函数</param>
            public static void LoadTextFileAsync(string url, Action<string> callback) 
            {
                TinyTool.Instance.StartCoroutine(LoadTextAsync(url, callback));
            }

            /// <summary>
            /// 异步加载文件
            /// </summary>
            /// <param name="url">文件地址</param>
            /// <param name="callback">加载文件结束后执行的回调函数</param>
            /// <returns>协程</returns>
            private static IEnumerator LoadByteAsync(string url,Action<byte[]> callback) 
            {
                UnityWebRequest request = UnityWebRequest.Get(url);
                request.timeout = 30;
                yield return request.SendWebRequest();
                if (request.isDone)
                {
                    byte[] data = request.downloadHandler.data;
                    if (data != null && data.Length > 0)
                        callback?.Invoke(data);
                    else
                        TLogTool.Error("加载的数据为空：" + url);
                }
            }
            
            private static IEnumerator LoadTextAsync(string url,Action<string> callback) 
            {
                UnityWebRequest request = UnityWebRequest.Get(url);
                request.timeout = 30;
                yield return request.SendWebRequest();

                if (request.isNetworkError)
                {
                    TLogTool.Error("下载资源错误：" + request.error);
                }
                else
                {
                    var text = request.downloadHandler.text;
                    if (!string.IsNullOrEmpty(text))
                        callback?.Invoke(text);
                    else
                        TLogTool.Error("加载的数据为空：" + url);
                }
            }
            #endregion

            #region SaveFile
            /// <summary>
            /// UTF8格式保存文本
            /// </summary>
            /// <param name="content">文本内容</param>
            /// <param name="filePath">保存的路径</param>
            /// <returns>是否保存成功</returns>
            public static bool SaveTextFile(string filePath,string content)
            {
                return SaveByteFile(filePath,Encoding.UTF8.GetBytes(content)); 
            }

            /// <summary>
            /// 保存字节文件
            /// </summary>
            /// <param name="data">字节数据</param>
            /// <param name="filePath">文件路径</param>
            /// <returns>是否保存成功</returns>
            public static bool SaveByteFile(string filePath,byte[] data)  
            {
                try
                {
                    if (string.IsNullOrEmpty(filePath))  return false;

                    string dirPath = System.IO.Path.GetDirectoryName(filePath);
                    if (string.IsNullOrEmpty(dirPath) == false && Directory.Exists(dirPath) == false)
                        Directory.CreateDirectory(dirPath);
                
                    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                    fs.Dispose();
                    
                    return true;
                }
                catch (Exception e)
                {
                    TLogTool.Error(e);
                    return false;
                }
                
            }
            #endregion
        }
    }
}

